import React, { Component } from 'react'
import PropTypes from 'prop-types'
import * as $helpers from './helpers'

export default class Input extends Component {
  static defaultProps = {
    as: 'input',
    type: 'text'
  }
  static contextTypes = {
    state: PropTypes.object,
    actions: PropTypes.object,
  }
  render() {
    const { state } = this.context
    const {
      as: Tag,
      name: path,
      ...restProps
    } = this.props
    if (path) {
      restProps['value'] = $helpers.getValueByPath(state, path)
    }
    restProps.onChange = this.handleChange
    return <Tag {...restProps} />
  }
  handleChange = event => {
    const { currentTarget } = event
    const { props, context } = this
    const {
      name: path,
      onChange,
    } = props
    const { state, actions } = context
    const currentValue = currentTarget.value
    if ('undefined' === typeof $helpers.getValueByPath(state, path)) {
      return
    }
    const globalState = $helpers.setValueByPath(state, path, currentValue)
    actions['UPDATE_INPUT_VALUE'](globalState)
    onChange && onChange(event)
  }
}
